import {nanoid, PageContainer, ProForm, ProFormText, ProFormDatePicker} from '@ant-design/pro-components';
import {Card, Col, Row, Space, Typography, message, Button, Modal, Upload, Form, DatePicker} from 'antd';
import React, {Component, useState} from 'react';
import {getYear, getYearFromRange, ShowError} from "@/utils/format";
import {
  DownloadApi,
  FillApi,
  GetSaveApi,
  SaveApi,
  SchoolCheckShow,
  ShowApi,
  UploadApi
} from "@/services/School/SchoolApi";
import {ServerMessages} from "@/services/ServerMessages";
import {history} from "umi";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";
import Submitter from "@/pages/Syl/Common/Submitter";
import moment from "moment";

class DisciFunds extends Component {
  state = {
    dataSource: [
      {
        key: nanoid(),
        yr: undefined,
        full_tch_num: '',
        ageblow25: '',
        age2535: '',
        age3645: '',
        age4660: '',
        ageup60: '',
        senior: '',
        sub_senior: '',
        mid_grade: '',
        other_grade: '',
        phd: '',
        m_degree: '',
        b_degree: '',
      },
    ],
    formRef: React.createRef()
  }

  // 点击按钮，在DataSource中添加一条数据
  handleAdd = () => {
    const {dataSource} = this.state
    dataSource.push({
      key: nanoid(),
      yr: undefined,
      full_tch_num: '',
      ageblow25: '',
      age2535: '',
      age3645: '',
      age4660: '',
      ageup60: '',
      senior: '',
      sub_senior: '',
      mid_grade: '',
      other_grade: '',
      phd: '',
      m_degree: '',
      b_degree: '',
    })
    this.setState({dataSource})
  }

  // 在DataSource中删除key值为value的项
  handleDelete = (value: string) => {
    return () => {

      const confirm = () => {
        let {dataSource} = this.state
        dataSource = dataSource.filter(item => {
          return item.key !== value
        })
        this.setState({dataSource})
        message.success('删除成功')
      }

      Modal.confirm({
        title: '确认删除？',
        onOk: confirm,
        onCancel: () => {}
      })
    }
  }

  render() {
    const status_is_check = history.location.query.id && history.location.query.fill_id
    const status_is_show = history.location.query.flag === 'display'
    const download = '3_2_3'
//上传
    const upload = UploadApi('/api/index/teacher-team/major-teacher/number-struct-template',
      (info) => {
        console.log("@success", info)
        if (info.file.response.status === 0) {
          const data = info.file.response.data['data_'+download]
          for (let i = 0; i < data.length; i++) {
            data[i].key = nanoid()
          }
          console.log(data)
          if (data.length > 0)
            this.setState({dataSource: data})
        } else {
          ShowError(info.file.response.message)
        }
      })
    const handleSaveBtn = () => {
      const value = this.state.formRef.current.getFieldsFormatValue()
      // 获取尾部 uuid （排除重复）
      const splitKeys = (values) => {
        const arr = []
        for (let key in values) {
          // console.log(key.split('-'))
          let tail = key.split('-')
          tail.shift()
          tail = tail.join('-')
          if (arr.indexOf(tail) === -1) {
            arr.push(tail)
          }
        }
        return arr
      }

      const arr = splitKeys(value)
      const genArr = []

      String.prototype.endWith = function(s) {
        const d = this.length - s.length;
        return d >= 0 && this.lastIndexOf(s) === d;
      };

      for (let i = 0; i < arr.length; i++) {
        const genObj = {}
        for (let k in value) {
          if (k.endsWith(arr[i])) {
            const kstr = k.split('-')
            if (kstr[0] === 'yr') {
              genObj[kstr[0]] = getYearFromRange(value[k])
            } else {
              genObj[kstr[0]] = value[k]
            }
          }
        }
        if (!genObj.yr) {
          genObj.yr = this.state.dataSource[i].yr
        }
        genArr.push(genObj)
      }

      const data = {
        fill_id: download,
        data: genArr
      }
      console.log("@请求数据", data)
      SaveApi('/api/temp-save', data).then(response => {
        if (response.status === 0) {
          Modal.success({
            title: <span>保存成功！</span>,
            onOk() {
              window.location.reload()
            }
          })
        } else {
          ShowError(response.message)
        }
      }, () => {
        ShowError(ServerMessages.error_message)
      })
    }

    return (
      <PageContainer
        title="学科专任教师数量及结构"
        content={<Typography.Text type="danger">1. 监测点内涵：2021年1月1日至今，学科专任教师数量及年龄结构、职称结构、学位结构情况。
          <br/>2. 学年度：请用“YYYY-YYYY”格式填报。
          <br/>3. 仅填写当前填报周期内新增的数据，如有删减，请告知学校管理员。
        </Typography.Text>}>
        <ProForm
          formRef={this.state.formRef}
          request={() => {
            return new Promise(resolve => {
              if (status_is_check) {
                SchoolCheckShow(history.location.query.id, history.location.query.fill_id)
                  .then(response => {
                    console.log("@response", response)
                    if (response.status === 0) {
                      // let initVal = {
                      //   "discipline_eval_turn_4": response.message[0].discipline_eval_result,
                      //   "discipline_eval_turn_5": response.message[1].discipline_eval_result,
                      //   "discipline_eval_turn_6": response.message[2].discipline_eval_result,
                      // }
                      // resolve(initVal)
                      let {dataSource} = this.state.dataSource
                      dataSource = response.message
                      for (let i = 0; i < dataSource.length; i++) {
                        dataSource[i].key = nanoid()
                      }
                      this.setState({dataSource: dataSource})
                      resolve(true)
                    } else {
                      resolve(true)
                    }
                  })
              } else if (status_is_show) {
                // 查看时加载内容
                ShowApi(download).then(response => {
                  console.log("@response", response)
                  if (response.status === 0) {
                    for (let i = 0; i < response.data.length; i++) {
                      response.data[i].key = nanoid()
                    }
                    this.setState({dataSource: response.data})
                    resolve(true)
                  }
                })
              } else {
                GetSaveApi('/api/show-temp-save', download).then(response => {
                  console.log("@response", response)
                  if (response.status === 0) {
                    for (let i = 0; i < response.data.length; i++) {
                      response.data[i].key = nanoid()
                    }
                    this.setState({dataSource: response.data})
                    resolve(true)
                    console.log(this.state.dataSource)
                  } else {
                    resolve(true)
                  }
                })
              }
            })
          }}
          onFinish={async (value) => {
            // 获取尾部 uuid （排除重复）
            const splitKeys = (values) => {
              const arr = []
              for (let key in values) {
                // console.log(key.split('-'))
                let tail = key.split('-')
                tail.shift()
                tail = tail.join('-')
                if (arr.indexOf(tail) === -1) {
                  arr.push(tail)
                }
              }
              return arr
            }

            const arr = splitKeys(value)
            const genArr = []

            String.prototype.endWith = function(s) {
              const d = this.length - s.length;
              return d >= 0 && this.lastIndexOf(s) === d;
            };

            for (let i = 0; i < arr.length; i++) {
              const genObj = {}
              for (let k in value) {
                if (k.endsWith(arr[i])) {
                  const kstr = k.split('-')
                  if (kstr[0] === 'yr') {
                    genObj[kstr[0]] = getYearFromRange(value[k])
                  } else {
                    genObj[kstr[0]] = value[k]
                  }
                }
              }
              if (!genObj.yr) {
                genObj.yr = this.state.dataSource[i].yr
              }
              genArr.push(genObj)
            }

            const queryString = {
              "data_3_2_3": genArr
            }

            console.log('@gen', genArr)
            console.log("@请求数据", queryString)
            return new Promise(resolve => {

              FillApi('/api/index/teacher-team/major-teacher/number-struct',
                queryString, (response) => {
                  message.success(response.message)
                  resolve(true)
                  history.push('/teacher-team/major-teacher')
                }, (response) => {
                  ShowError(response.message)
                  resolve(false)
                }, () => {
                  ShowError(ServerMessages.error_message)
                  resolve(false)
                })

            })
          }}
          submitter={{
            render: (props, doms) => {
              return <Submitter
                upload={upload}
                download={download}
                doms={doms}
                save={handleSaveBtn}
              />
            },
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
            submitButtonProps: {
              style: {
                marginLeft: '-8px'
              }
            },
          }}
        >
          {
            this.state.dataSource.map((item, idx) => {
              return <Space key={item.key} direction="vertical" size="middle" style={{display: 'flex'}}>
                <Card bordered={false} style={{marginBottom: 20}}>
                  <ProForm.Group>

                    <Form.Item label="学年度" name={"yr-" + item.key}>
                      <DatePicker.RangePicker
                        // name={"yr-" + item.key}
                        defaultValue={String(this.state.dataSource[idx].yr).split("-").length === 2 ? [moment(String(this.state.dataSource[idx].yr).split("-")[0], 'YYYY'),moment(String(this.state.dataSource[idx].yr).split("-")[1], 'YYYY')] : []}
                        picker="year"
                        // format="YYYY"
                        onChange={(date, dateString) => {
                          for (let i = 0; i < this.state.dataSource.length; i++) {
                            if (this.state.dataSource[i].key === item.key) {
                              this.state.dataSource[i].yr = dateString.join('-')
                              this.setState({dataSource: this.state.dataSource})
                              break
                            }
                          }
                        }
                        }
                      />
                    </Form.Item>

                    {/*<ProFormDatePicker*/}
                    {/*  placeholder="请输入年度"*/}
                    {/*  name={"yr-"+item.key}*/}
                    {/*  label="年度"*/}
                    {/*  picker="year"*/}
                    {/*  format="YYYY"*/}
                    {/*  initialValue={this.state.dataSource[idx].yr} />*/}

                    <ProFormText
                      width="md"
                      name={"full_tch_num-"+item.key}
                      label="专任教师总数"
                      placeholder="专任教师总数"
                      initialValue={this.state.dataSource[idx].full_tch_num}
                    />

                  </ProForm.Group>
                  <ProForm.Group
                    title="年龄结构">
                    <ProFormText
                      width="md"
                      name={"ageblow25-"+item.key}
                      label="25岁以下"
                      placeholder="25岁以下"
                      initialValue={this.state.dataSource[idx].ageblow25}
                    />
                    <ProFormText
                      width="md"
                      name={"age2535-"+item.key}
                      label="25-35"
                      placeholder="25-35"
                      initialValue={this.state.dataSource[idx].age2535}
                    />
                    <ProFormText
                      width="md"
                      name={"age3645-"+item.key}
                      label="36-45"
                      placeholder="36-45"
                      initialValue={this.state.dataSource[idx].age3645}
                    />
                    <ProFormText
                      width="md"
                      name={"age4660-"+item.key}
                      label="46-60"
                      placeholder="46-60"
                      initialValue={this.state.dataSource[idx].age4660}
                    />
                    <ProFormText
                      width="md"
                      name={"ageup60-"+item.key}
                      label="60岁以上"
                      placeholder="60岁以上"
                      initialValue={this.state.dataSource[idx].ageup60}
                    />
                  </ProForm.Group>
                  <ProForm.Group
                    title="职称结构">
                    <ProFormText
                      width="md"
                      name={"senior-"+item.key}
                      label="正高级"
                      placeholder="正高级"
                      initialValue={this.state.dataSource[idx].senior}
                    />
                    <ProFormText
                      width="md"
                      name={"sub_senior-"+item.key}
                      label="副高级"
                      placeholder="副高级"
                      initialValue={this.state.dataSource[idx].sub_senior}
                    />
                    <ProFormText
                      width="md"
                      name={"mid_grade-"+item.key}
                      label="中级"
                      placeholder="中级"
                      initialValue={this.state.dataSource[idx].mid_grade}
                    />
                    <ProFormText
                      width="md"
                      name={"other_grade-"+item.key}
                      label="其他"
                      placeholder="其他"
                      initialValue={this.state.dataSource[idx].other_grade}
                    />
                  </ProForm.Group>
                  <ProForm.Group
                    title="学位结构">
                    <ProFormText
                      width="md"
                      name={"phd-"+item.key}
                      label="博士"
                      placeholder="博士"
                      initialValue={this.state.dataSource[idx].phd}
                    />
                    <ProFormText
                      width="md"
                      name={"m_degree-"+item.key}
                      label="硕士"
                      placeholder="硕士"
                      initialValue={this.state.dataSource[idx].m_degree}
                    />
                    <ProFormText
                      width="md"
                      name={"b_degree-"+item.key}
                      label="其他"
                      placeholder="其他"
                      initialValue={this.state.dataSource[idx].b_degree}
                    />
                  </ProForm.Group>
                  {idx > 0 && !(status_is_check||status_is_show) && (
                    <Button onClick={this.handleDelete(item.key)} type="primary" danger>删除</Button>
                  )}
                </Card>
              </Space>
            })
          }
          {!(status_is_check||status_is_show) && <Button onClick={this.handleAdd} type="dashed" style={{width: '100%', marginBottom: 20}}>添加一行</Button>}
        </ProForm>
      </PageContainer>
    );
  }
}

export default DisciFunds;
